/**
 * User: Ruslan Mikhaylenko mirunet@gmail.com
 * Date: 01.05.13
 * Time: 21:28
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadInThread extends Thread {

    private final Process process;
    private final String filename;
    private final String playlist;

    ReadInThread(Process p, String f, String pl) {
        this.process = p;
        this.filename = f;
        this.playlist = pl;
    }

    @Override
    public void run() {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String seconds_pattern = "ANS_time_pos";
        String exit_pattern = "Exiting... \\(End of file\\)";
        String quit_pattern = "Exiting... \\(Quit\\)";
        String sleep_pattern = "VFCTRL_SCREENSHOT";

        Pattern seconds_pattern_compiled = Pattern.compile(seconds_pattern);
        Pattern exit_pattern_compiled = Pattern.compile(exit_pattern);
        Pattern quit_pattern_compiled = Pattern.compile(quit_pattern);
        Pattern sleep_pattern_compiled = Pattern.compile(sleep_pattern);

        try {
            String line;
            while ((line = br.readLine()) != null) {
                //System.out.println(line);
                Matcher m = seconds_pattern_compiled.matcher(line);
                Matcher e = exit_pattern_compiled.matcher(line);
                Matcher q = quit_pattern_compiled.matcher(line);
                Matcher s = sleep_pattern_compiled.matcher(line);


                if (m.find()) {
                    FilesUtils.insertrecord(filename, playlist, line);
                } else if (e.find()) {
                    FilesUtils.insertrecord(filename, playlist, "ANS_time_pos=0");
                } else if (s.find()) {
                    Shutdown.setShutdownTime();
                    System.out.println("SETTING: Shutdown in " + Math.round((Shutdown.getShutdownTime() - System.currentTimeMillis()) / 60000) + " minutes");
                } else if (q.find()) {
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("CHILD FINISHED");
    }
}


